from PySide6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QLabel, QFrame, \
    QAbstractItemView
from PySide6.QtCore import Qt,Signal,Slot
from PySide6.QtGui import QPixmap, QFont, QDesktopServices, QMouseEvent

from threading import Thread
from core.get_url import getIcon

with open('setting','r',encoding='utf-8') as data:
    lines = data.readlines()
    DEFAULTURLS = eval(lines[0].split('=',maxsplit=1)[1].replace('\n',''))

class shortcutsBar(QTableWidget):
    cols = 5
    rows = 2
    changeCell = Signal(str,str)
    addCell = Signal(int,int,str,str)
    def __init__(self, parent=None):
        super().__init__(parent)
        self.changeCellPos = None
        self.cellDict = {
            0:{},
            1:{}
        }

        self.bind()
        self.initSetup()

    def bind(self):
        self.addCell.connect(self.setCellEvent)

    def initSetup(self):
        self.setFixedSize(551, 221)
        self.setCursor(QPixmap('./img/mouse3.png'))
        self.setColumnCount(shortcutsBar.cols)
        self.setRowCount(shortcutsBar.rows)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)  # 设置水平滑动跳为关闭
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)  # 设置垂直滑动跳为关闭
        self.horizontalHeader().setVisible(False)  # 关闭左侧行数
        self.verticalHeader().setVisible(False)  # 关闭表头
        self.setAutoScroll(False)

        # # bug 父类为QWidget行高和列宽无效 以下为替代方法
        self.horizontalHeader().setMinimumSectionSize(110)
        self.verticalHeader().setMinimumSectionSize(110)

        self.setFrameShape(QFrame.Shape.NoFrame) # 取消边框线
        self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)

        self.setEditTriggers(self.EditTrigger.NoEditTriggers) # 设置表格中单元格不可编辑

        for index,key in enumerate(DEFAULTURLS.keys()):
            row = 0
            if index > 5:
                index -= 5
                row = 1

            currentThreading = Thread(target=self.cellInit,
                                      args=(row,index,DEFAULTURLS[key],key,))
            currentThreading.start()

    @Slot(str,str)
    def setCell(self,name,url):
        row, col = self.changeCellPos

        if not name or not url:
            item = self.cellDict[row][col]
            with open('setting','r+',encoding='utf-8') as data:
                t = data.read()
                startIndex = t.find('DEFAULTURLS')
                endIndex = t.find('}', startIndex)
                name, value = t[startIndex:endIndex + 1].split('=', 1)
                value = eval(value)
                value.pop(item[1])
                value = str(value)
                newText = name + '=' + value
                newT = t.replace(t[startIndex:endIndex + 1], newText)

                data.seek(0)
                data.truncate()
                data.write(newT)
            self.cellDict[row].pop(col)
            self.removeCellWidget(row,col)

        else:
            DEFAULTURLS[name] = url
            currentThreading = Thread(target=self.cellInit,
                                      args=(row, col, url, name,),
                                      kwargs={'isAdd':True})
            currentThreading.start()

    @Slot(int,int,str,str)
    def setCellEvent(self,row:int,col:int,img:str,text:str):
        cell = QWidget()
        cellLayout = QVBoxLayout(cell)
        cellText = QLabel(text)
        cellText.setFont(QFont('微软雅黑',12))
        cellText.setStyleSheet('color: #ffffff')

        cellIcon = iconLabel(f'./img/{img}.ico',text)

        cellLayout.addWidget(cellIcon,alignment=Qt.AlignmentFlag.AlignCenter)
        cellLayout.addWidget(cellText,alignment=Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignBottom)

        self.setCellWidget(row,col,cell)

    def cellInit(self,row:int,col:int,url:str,text:str,isAdd:bool=False):
        self.cellDict[row][col] = (url, text)
        img = getIcon(url)

        if isAdd:
            with open('setting','r+',encoding='utf-8') as data:
                t = data.read()
                startIndex = t.find('DEFAULTURLS')
                endIndex = t.find('}',startIndex)
                name,value = t[startIndex:endIndex+1].split('=',1)
                value = eval(value)
                value[text] = url
                value = str(value)
                newText = name + '=' + value
                newT = t.replace(t[startIndex:endIndex+1],newText)

                data.seek(0)
                data.truncate()
                data.write(newT)

        self.addCell.emit(row,col,img,text)

    def mouseDoubleClickEvent(self, event:QMouseEvent) -> None:
        if event.button() == Qt.MouseButton.RightButton:
            pos = event.pos()
            self.changeCellPos = (self.rowAt(pos.y()),self.columnAt(pos.x()))
            data = self.cellDict.get(self.changeCellPos[0],None).get(self.changeCellPos[1],None)
            if data is not None:
                self.changeCell.emit(data[0],data[1])
            else:
                self.changeCell.emit(None, None)
class iconLabel(QLabel):
    def __init__(self, iconPath:str, iconText:str,parent=None):
        super().__init__(parent)
        self.iconPath = iconPath
        self.iconText = iconText

        self.initSetup()

    def initSetup(self):
        self.setPixmap(QPixmap(self.iconPath))
        self.setContentsMargins(0,0,0,0)
        self.setCursor(QPixmap('./img/mouse4.png'))

    def mouseReleaseEvent(self, ev):
        if 0 <= ev.pos().x() <= self.width() and 0 <= ev.pos().y() <= self.height():
            if ev.button() == Qt.MouseButton.LeftButton:
                QDesktopServices.openUrl(DEFAULTURLS[self.iconText])